package db

import (
	"fmt"
	"log"
	"reflect"
	"time"

	"loghub/model"
)

// init 初始化数据库的表结构等
func init() {
	checkUserTable()
	checkUserSessionTable()
	checkProjectInfoTable()
	checkLogDetailDataTable()
	checkLogTraceInfoTable()
}

func checkUserTable() {
	scalar, _, err := QueryScalarFloat64("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='user';")
	if err != nil {
		log.Println(err)
		return
	}

	if scalar == 0 {
		// 需要初始化user表
		_, err := ExecSQL("CREATE TABLE user (id integer not null primary key AUTOINCREMENT, username text,password text)")
		if err != nil {
			log.Println(err)
			return
		}

		// 添加管理员用户
		_, err = ExecSQL("insert into user values (null,'admin','admin666')")
		if err != nil {
			log.Println(err)
			return
		}
	}

	var user model.User
	err = QueryStructByReflect("select * from user limit 1;", &user)
	if err != nil {
		log.Println(err)
		return
	}
	fmt.Println("当前用户是: ", user)
}

func checkUserSessionTable() {
	scalar, _, err := QueryScalarFloat64("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='user_session';")
	if err != nil {
		log.Println(err)
		return
	}

	if scalar == 0 {
		// 需要初始化user表
		_, err := ExecSQL("CREATE TABLE user_session (sid text not null primary key,userid integer not null, username text,createtime text,expiretime int not null)")
		if err != nil {
			log.Println(err)
			return
		}
	}

	// 清除已过期的Session
	values, err := QueryStructListByReflect("SELECT * FROM user_session", reflect.TypeOf(model.UserSession{}))
	if err != nil {
		log.Println(err)
		return
	}
	for _, v := range values {
		if userSession, ok := v.(model.UserSession); ok {
			if int(time.Now().Sub(userSession.CreateTime).Seconds()) > userSession.ExpireTime {
				// Session过期, 删除session
				_, err := ExecSQL(fmt.Sprintf("delete from user_session where sid='%s'", userSession.Sid))
				if err != nil {
					log.Println(err)
					return
				}
			}
		}
	}
}

func checkProjectInfoTable() {
	scalar, _, err := QueryScalarFloat64("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='project_info';")
	if err != nil {
		log.Println(err)
		return
	}

	if scalar == 0 {
		// 需要初始化user表
		_, err := ExecSQL("CREATE TABLE project_info (ProjectID text not null primary key,ProjectName text not null, ProjectPlatform text not null,Cretor text not null,CreateTime text not null)")
		if err != nil {
			log.Println(err)
			return
		}
	}
}

func checkLogDetailDataTable() {
	scalar, _, err := QueryScalarFloat64("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='log_detail_data';")
	if err != nil {
		log.Println(err)
		return
	}

	if scalar == 0 {
		// 需要初始化user表
		var sql = `CREATE TABLE log_detail_data 
		(TraceID text not null primary key,
		ProjectID text not null,
		LogLevel text not null,
		LogTitle text not null,
		LogContent text not null,
		HTTPStatusCode integer not null,
		StackTrace text not null,
		ErrorType text not null,
		AssemblyName text not null,
		ProcessName text not null,
		ProcessID integer not null,
		PackageName text not null,
		FunctionName text not null,
		ClientIP text not null,
		Remark text not null,
		CreateTime text not null)`
		_, err := ExecSQL(sql)
		if err != nil {
			log.Println(err)
			return
		}
	}
}

func checkLogTraceInfoTable() {
	scalar, _, err := QueryScalarFloat64("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='log_trace_info';")
	if err != nil {
		log.Println(err)
		return
	}

	if scalar == 0 {
		// 需要初始化user表
		var sql = `CREATE TABLE log_trace_info 
		(RPCTraceID text not null primary key,
		TraceID text not null,
		LogTitle text not null,
		LogContent text not null,
		StackTrace text not null,
		ErrorType text not null,
		AssemblyName text not null,
		ProcessName text not null,
		ProcessID integer not null,
		PackageName text not null,
		FunctionName text not null,
		ClientIP text not null,
		OSName text not null,
		Remark text not null,
		CreateTime text not null)`
		_, err := ExecSQL(sql)
		if err != nil {
			log.Println(err)
			return
		}
	}
}
